package com.itheima.service.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Lists;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import sun.util.calendar.LocalGregorianCalendar;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    OrderSettingMapper orderSettingMapper;

    //创建一个定长的线程池
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

    @Override
    public void setNumberByDate(OrderSetting orderSetting) {
        //根据日期查询是否存在预约设置
        Integer count = orderSettingMapper.findCountByDate(orderSetting.getOrderDate());
        if (null != count && count > 0) {
            //存在就更新
            orderSettingMapper.edit(orderSetting);
        } else {
            //不存在就插入
            orderSettingMapper.add(orderSetting);
        }
    }

    @Override
    public void batchSave(List<OrderSetting> params) {
//        for (OrderSetting param : params) {
//            setNumberByDate(param);
//        }
        //多线程
        List<List<OrderSetting>> partition = Lists.partition(params, 50);
        for (List<OrderSetting> orderSettings : partition) {
            fixedThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    for (OrderSetting orderSetting : orderSettings) {
                        setNumberByDate(orderSetting);
                    }
                }
            });
        }
    }

    @Override
    public List<OrderSetting> findByMonth(String date) {
        String start = date + "-01";
        String end = date + "-31";
        List<OrderSetting> orderSettings = orderSettingMapper.findByMonth(start, end);
        return orderSettings;
    }

    @Override
    public void cleanOrderSetting(DateTime dateTime) {
        orderSettingMapper.cleanOrderSetting(dateTime);
    }


}
